﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Xml;
using ModbusDataParseTool.Entity;
using ModbusDataParseTool.Utility;
using MyUtility.Utility;

namespace ModbusDataParseTool.Service
{
    public class GetConfigService
    {
        private string filePath = "";
        public string ScriptServerIP { get; set; }

        public int ScriptServerPort { get; set; }

        public int LocalPort { get; set; }
        public string LocalIP { get; set; }
        public int CommType { get; set; }


        public GetConfigService()
        {
            filePath = System.AppDomain.CurrentDomain.BaseDirectory;
        }

        public bool ReadScriptServiceConfig()
        {
            bool isRight = false;
            //判断是否存在配置文件
            string fileSysCfgPath = filePath + "CFG\\SysCfg.ini";
            if (File.Exists(fileSysCfgPath))
            {
                //读取IP和端口
                string ServerIPStr = INIHelper.Read("本机", "服务器IP", "-1", fileSysCfgPath);
                string ServerPortStr = INIHelper.Read("本机", "服务器port", "-1", fileSysCfgPath);


                if (CheckStrNum.CheckStrIsFourDot(ServerIPStr))
                {
                    ScriptServerIP = ServerIPStr;
                }
                else
                {
                    ScriptServerIP = "127.0.0.1";
                }
                if (CheckStrNum.CheckStrIsInteger(ServerPortStr) && !"-1".Equals(ServerPortStr))
                {
                    ScriptServerPort = Convert.ToInt32(ServerPortStr);
                }
                else
                {
                    ScriptServerPort = 6789;
                }
                isRight = true;
            }
            return isRight;
        }

        public bool ReadCommTypeConfig(ref int commType)
        {
            bool isRight = false;
            //获取程序所在路径
            string filePath = System.AppDomain.CurrentDomain.BaseDirectory;
            //判断是否存在配置文件
            string fileSysCfgPath = filePath + "CFG\\SysCfg.ini";
            if (File.Exists(fileSysCfgPath))
            {
                //读取IP和端口
                string commTypeStr = INIHelper.Read("本机", "通信方式", "-1", fileSysCfgPath);

                if (CheckStrNum.CheckStrIsInteger(commTypeStr) && !"-1".Equals(commTypeStr))
                {
                    commType = Convert.ToInt32(commTypeStr);
                }
                else
                {
                    commType = 1;
                }

                isRight = true;
            }
            return isRight;
        }

        public bool ReadTCPConfig()
        {
            bool isRight = false;
            //获取程序所在路径
            string filePath = System.AppDomain.CurrentDomain.BaseDirectory;
            //判断是否存在配置文件
            string fileSysCfgPath = filePath + "CFG\\SysCfg.ini";
            if (File.Exists(fileSysCfgPath))
            {
                //读取IP和端口
                string LocalIPStr = INIHelper.Read("本机", "本机IP", "-1", fileSysCfgPath);
                string LocalPortStr = INIHelper.Read("本机", "本机端口", "-1", fileSysCfgPath);
                string commType = INIHelper.Read("本机", "通信方式", "-1", fileSysCfgPath);

                if (CheckStrNum.CheckStrIsFourDot(LocalIPStr))
                {
                    LocalIP = LocalIPStr;
                }
                else
                {
                    LocalIP = "127.0.0.1";
                }
                if (CheckStrNum.CheckStrIsInteger(LocalPortStr) && !"-1".Equals(LocalPortStr))
                {
                    LocalPort = Convert.ToInt32(LocalPortStr);
                }
                else
                {
                    LocalPort = 5560;
                }


                if (CheckStrNum.CheckStrIsInteger(commType) && !"-1".Equals(commType))
                {
                    CommType = Convert.ToInt32(commType);
                }
                else
                {
                    CommType = 0;
                }

                isRight = true;
            }
            return isRight;
        }
        
        public bool ReadTCPAndComConfig(ref CommInfoEntity commInfoEntity)
        {
            bool isRight = false;
            if (commInfoEntity != null)
            {
                commInfoEntity = new CommInfoEntity();
            }
            //获取程序所在路径
            string filePath = System.AppDomain.CurrentDomain.BaseDirectory;
            //判断是否存在配置文件
            string fileComInfoPath = filePath + "CFG\\ComCfg\\ComInfo.ini";
            if (File.Exists(fileComInfoPath))
            {
                //读取通信方式
                string CommTypeStr = INIHelper.Read("通信配置", "通信方式", "-1", fileComInfoPath);
                if (CheckStrNum.CheckStrIsInteger(CommTypeStr) && !"-1".Equals(CommTypeStr))
                {
                    int commTypeInfo = Convert.ToInt32(CommTypeStr);
                    if (Enum.IsDefined(typeof(CommTypeInfo), commTypeInfo))
                    {
                        commInfoEntity.CommType = (CommTypeInfo)commTypeInfo;
                    }
                    else
                    {
                        commInfoEntity.CommType = 0;
                    }
                }
                else
                {
                    commInfoEntity.CommType = 0;
                }


                #region 读取Server IP和端口

                string LocalIPStr = "127.0.0.1";
                int LocalPort = 5555;
                ReadTCPAndComConfig(fileComInfoPath, "TCP服务端配置", "本机IP", "本机端口", 1, ref LocalIPStr, ref LocalPort);
                commInfoEntity.TCPServerIP = LocalIPStr;
                commInfoEntity.TCPServerProt = LocalPort;

                #endregion

                #region 读取Client IP和端口

                string ClientLocalIP = "127.0.0.1";
                int ClientLocalPort = 5555;
                ReadTCPAndComConfig(fileComInfoPath, "TCP客户端配置", "本机IP", "本机端口", 1, ref ClientLocalIP, ref ClientLocalPort);

                commInfoEntity.TCPClientLocalIP = ClientLocalIP;
                commInfoEntity.TCPClientLocalProt = ClientLocalPort;


                string ClientRemoteIP = "127.0.0.1";
                int ClientRemotePort = 5556;
                ReadTCPAndComConfig(fileComInfoPath, "TCP客户端配置", "服务器IP", "服务器端口", 1, ref ClientRemoteIP, ref ClientRemotePort);
                commInfoEntity.TCPClientIP = ClientRemoteIP;
                commInfoEntity.TCPClientProt = ClientRemotePort;

                #endregion

                #region 读取串口

                string SerialNameStr = "COM1";
                int SerialBaudRate = 9600;
                ReadTCPAndComConfig(fileComInfoPath, "串口配置", "串口号", "波特率", 2, ref SerialNameStr, ref SerialBaudRate);
                commInfoEntity.ComProtName = SerialNameStr;
                commInfoEntity.ComBaudRate = SerialBaudRate;

                #endregion

                isRight = true;
            }
            return isRight;
        }

        
        private bool ReadTCPAndComConfig(string filePath, string sectionKey, string IPKey, string PortKey, int type, ref string qkServerIP, ref int qkServerPort)
        {
            bool isRight = false;

            //读取IP和端口
            string qkServerIPStr = INIHelper.Read(sectionKey, IPKey, "-1", filePath);
            string qkServerPortStr = INIHelper.Read(sectionKey, PortKey, "-1", filePath);

            if (!CheckStrNum.CheckStrIsInteger(qkServerPortStr) || 
                "-1".Equals(qkServerIPStr) || "-1".Equals(qkServerPortStr))
            {
                isRight = false;
            }
            else
            {
                if (type == 1 && !CheckStrNum.CheckStrIsFourDot(qkServerIPStr))
                {
                    //校验为网路通信时，名称为4个点
                    isRight = false;
                }
                else
                {
                    isRight = true;
                }
            }

            if (isRight)
            {
                qkServerIP = qkServerIPStr; 
                qkServerPort = Convert.ToInt32(qkServerPortStr);
            }


            return isRight;
        }

        public bool ReadTCPClientConfig(ref string qkServerIP, ref int qkServerPort)
        {
            bool isRight = false;
            //获取程序所在路径
            string filePath = System.AppDomain.CurrentDomain.BaseDirectory;
            //判断是否存在配置文件
            string fileSysCfgPath = filePath + "CFG\\SysCfg.ini";
            if (File.Exists(fileSysCfgPath))
            {
                //读取IP和端口
                string qkServerIPStr = INIHelper.Read("本机", "缺口服务器IP", "-1", fileSysCfgPath);
                string qkServerPortStr = INIHelper.Read("本机", "缺口服务器端口", "-1", fileSysCfgPath);

                if (!CheckStrNum.CheckStrIsFourDot(qkServerIPStr))
                {
                    qkServerIP = "127.0.0.1";
                }
                else
                {
                    qkServerIP = qkServerIPStr;
                }

                if (!CheckStrNum.CheckStrIsInteger(qkServerPortStr) || "-1".Equals(qkServerPortStr))
                {
                    qkServerPort = 5011;
                }
                else
                {
                    qkServerPort = Convert.ToInt32(qkServerPortStr);
                }

                isRight = true;
            }
            return isRight;
        }

        public bool ReadTelCode(out string telCode)
        {
            bool isRight = false;
            telCode = "";
            //判断是否存在配置文件
            string fileSysCfgPath = filePath + "CFG\\SysCfg.ini";
            if (File.Exists(fileSysCfgPath))
            {
                //读取IP和端口
                telCode = INIHelper.Read("本机", "站名", "-1", fileSysCfgPath);

                if (string.IsNullOrEmpty(telCode) || "-1".Equals(telCode))
                {
                    return isRight;
                }

                isRight = true;
            }
            return isRight;
        }
        
        public bool ReadIdentCode(out string identCode)
        {
            bool isRight = false;
            identCode = "";
            //判断是否存在配置文件
            string fileSysCfgPath = filePath + "CFG\\SysCfg.ini";
            if (File.Exists(fileSysCfgPath))
            {
                //读取IP和端口
                identCode = INIHelper.Read("本机", "识别码", "-1", fileSysCfgPath);

                if (string.IsNullOrEmpty(identCode) || "-1".Equals(identCode))
                {
                    return isRight;
                }
                identCode = Regex.Replace(identCode, @"\s", "");
                isRight = true;
            }
            return isRight;
        }


        public bool ReadLKTypeCode(out int LKTypeCode)
        {
            bool isRight = false;
            LKTypeCode = -1;
            //判断是否存在配置文件
            string fileSysCfgPath = filePath + "CFG\\SysCfg.ini";
            if (File.Exists(fileSysCfgPath))
            {
                //读取IP和端口
                string LKTypeCodeStr = INIHelper.Read("本机", "模拟类型", "-1", fileSysCfgPath);

                if (string.IsNullOrEmpty(LKTypeCodeStr) || "-1".Equals(LKTypeCodeStr))
                {
                    return isRight;
                }
                LKTypeCode = Convert.ToInt32(LKTypeCodeStr);
                isRight = true;
            }
            return isRight;
        }


        public bool ReadDelayTime(ref int DealyTime)
        {
            bool isRight = false;
            string DealyTimeStr = "";
            //判断是否存在配置文件
            string fileConfigPath = filePath + "CFG\\config.ini";
            if (File.Exists(fileConfigPath))
            {
                //读取IP和端口
                DealyTimeStr = INIHelper.Read("网络控制", "默认延迟", "-1", fileConfigPath);

                if (string.IsNullOrEmpty(DealyTimeStr) || "-1".Equals(DealyTimeStr) || !CheckStrNum.CheckStrIsInteger(DealyTimeStr))
                {
                    DealyTime = 5;
                }
                else
                {
                    DealyTime = Convert.ToInt32(DealyTimeStr);
                }
                
                isRight = true;
            }

            return isRight;
        }

        public bool ReadBaseInfo(ref List<BaseInfoCfgEntity> baseInfoCfgEnts)
        {
            bool isRight = false;
            if (baseInfoCfgEnts == null)
            {
                baseInfoCfgEnts = new List<BaseInfoCfgEntity>();
            }
            //路径
            string fileBaseCfgPath = filePath + "CFG\\基本信息.ini";
            if (File.Exists(fileBaseCfgPath))
            {
                //读取IP和端口
                string numStr = INIHelper.Read("协议解析", "总数", "-1", fileBaseCfgPath);
                if (string.IsNullOrEmpty(numStr) || "-1".Equals(numStr) || !MyUtility.Utility.CheckStrNum.CheckStrIsInteger(numStr))
                {
                    return isRight;
                }
                //转换总数
                int stationNum = Convert.ToInt32(numStr);
                for (int i = 0; i < stationNum; i++)
                {
                    string keyWord = (i + 1).ToString();
                    string stationStr = INIHelper.Read("协议解析", keyWord, "-1", fileBaseCfgPath);
                    if (string.IsNullOrEmpty(stationStr) || "-1".Equals(stationStr))
                    {
                        continue;
                    }
                    //分割
                    stationStr = Regex.Replace(stationStr, @"\s", "");
                    string[] stationWords = stationStr.Split(',', '，');
                    if (stationWords.Length >= 3 && MyUtility.Utility.CheckStrNum.CheckStrIsInteger(stationWords[1]))
                    {
                        int stationCodeNum = Convert.ToInt32(stationWords[1]);
                        BaseInfoCfgEntity baseInfoCfgEntTemp = new BaseInfoCfgEntity(i + 1, stationWords[0], stationCodeNum, stationWords[2]);
                        baseInfoCfgEnts.Add(baseInfoCfgEntTemp);
                    }                    
                }

                if (baseInfoCfgEnts.Count > 0)
                {
                    isRight = true;
                }
            }
            else
            {
                return isRight;
            }

            return isRight;
        }

        /// <summary>
        /// 读取通用的XML文件类型
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="path"></param>
        /// <param name="lKDevStatus"></param>
        /// <returns></returns>
        public bool ReadStandardXMLToClass<T>(string path, ref T lKDevStatus)
        {
            bool isRight = false;
            string fileCommPath = filePath + path;

            if (!File.Exists(fileCommPath))
            {
                return isRight;
            }

            try
            {
                lKDevStatus = MyUtility.Utility.DeserializeToXmlTool.DeserializeFromXml<T>(fileCommPath);
                isRight = true;
            }
            catch (Exception e)
            {
                LogHelper.WriteLog("ReadDevStatusXML", e);
            }

            return isRight;
        }



    }
}
